//
//  InfoSetUpViewController.m
//  TQY
//
//  Created by 甘世清 on 2024/10/7.
//

#import "InfoSetUpViewController.h"
#import "GenderPopView.h"
#import <BRPickerView/BRPickerView.h>
#import "SQCLLocationManager.h"
#import "ViewController.h"
@interface InfoSetUpViewController ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@property (nonatomic , strong) HeaderView  * tijiaoBtn;

@property (nonatomic , strong) HeaderView  * headerView;//头像
@property (nonatomic , strong) GenderPopView * genderView;//性别
@property (nonatomic , strong) UITextField * nameTextField;//名字
@property (nonatomic , strong) HeaderView  * birthday;
@property (nonatomic , strong) UITextField * wxTextField;//名字
@property (nonatomic , strong) HeaderView  * city;
@property (nonatomic , strong) FSTextView * aboutMeTextView;//关于我
@property (nonatomic ) BOOL   isHeaderImage;

@end

@implementation InfoSetUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = SQNSLocalString(@"个人资料");
    [self.zx_navBar addSubview:self.tijiaoBtn];
    [self.tijiaoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(30);
        make.centerY.equalTo(self.zx_navTitleLabel);
        make.right.equalTo(self.view.mas_right).offset(-10);
    }];
    self.view.backgroundColor = UIColor.whiteColor;
    
    if ([SKStoreReviewController respondsToSelector:@selector(requestReviewInScene:)]) {
        NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *windowScene = (UIWindowScene *)array[0];
        [SKStoreReviewController requestReviewInScene:windowScene];
    }
}
- (void)SQ_UIViewForSelfView{
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(SCREEN_WIDETH, SCREEN_HEIGHT+80);
    scrollView.showsVerticalScrollIndicator = FALSE;
    [self.view addSubview:scrollView];
    scrollView.backgroundColor =  UIColor.clearColor;
    UIView * bgView = [[UIView alloc]init];
    bgView.backgroundColor =  UIColor.whiteColor;
    [scrollView addSubview:bgView];
     [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.top.equalTo(scrollView);
         make.width.mas_equalTo(SCREEN_WIDETH);
         make.height.mas_equalTo(900);
    }];
    UIImageView * bgImageView = [[UIImageView alloc]init];
    bgImageView.image = SQGetImage(@"二级背景");
    bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    [bgView addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(bgView);
    }];
    [bgView addSubview:self.headerView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(88);
        make.top.equalTo(bgView).offset(TopHeight+10);
        make.centerX.equalTo(bgView);
    }];
    UIImageView * imageView = [[UIImageView alloc]init];
    imageView.image = SQGetImage(@"传照片");
    [bgView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(30);
            make.bottom.right.equalTo(self.headerView);
    }];
    
    UILabel * label1  = [[UILabel alloc]init];
    label1.text = SQNSLocalString(@"昵称");
    label1.font = FONT_MEDIUM(14);
    label1.textColor = SQColor999999;
    [bgView addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(16);
        make.top.equalTo(self.headerView.mas_bottom).offset(24);
    }];
    [bgView addSubview:self.nameTextField];
    [self.nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH-100);
            make.height.mas_equalTo(48);
            make.centerX.equalTo(bgView);
            make.top.equalTo(label1.mas_bottom).offset(8);
    }];
    
    UILabel * label33  = [[UILabel alloc]init];
    label33.text = SQNSLocalString(@"微信");
    label33.font = FONT_MEDIUM(14);
    label33.textColor = SQColor999999;
    [bgView addSubview:label33];
    [label33 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(16);
        make.top.equalTo(label1.mas_bottom).offset(80);
    }];
    [bgView addSubview:self.wxTextField];
    [self.wxTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH-100);
            make.height.mas_equalTo(48);
            make.centerX.equalTo(bgView);
            make.top.equalTo(label33.mas_bottom).offset(8);
    }];
    
    UILabel * label5  = [[UILabel alloc]init];
    label5.text = SQNSLocalString(@"签名");
    label5.font = FONT_MEDIUM(14);
    label5.textColor = SQColor999999;
    [bgView addSubview:label5];
    [label5 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(16);
        make.top.equalTo(label33.mas_bottom).offset(80);
    }];
    UIView * bgTextView = [[UIView alloc]init];
    bgTextView.backgroundColor = SQColor(@"#FFFFFF");
    bgTextView.layer.cornerRadius = 24;
    bgTextView.layer.masksToBounds = YES;
    [bgView addSubview:bgTextView];
    
    [bgView addSubview:self.aboutMeTextView];
    [self.aboutMeTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH-108);
            make.height.mas_equalTo(40);
            make.centerX.equalTo(bgView);
            make.top.equalTo(label5.mas_bottom).offset(10);
    }];
    [bgTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.aboutMeTextView).insets(UIEdgeInsetsMake(-4, -4, -4, -4));
    }];
    
    UILabel * label2  = [[UILabel alloc]init];
    label2.text = SQNSLocalString(@"性别");
    label2.font = FONT_MEDIUM(14);
    label2.textColor = SQColor999999;
    [bgView addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(16);
        make.top.equalTo(self.aboutMeTextView.mas_bottom).offset(20);
    }];
    
    [bgView addSubview:self.genderView];
    [self.genderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(bgView);
            make.top.equalTo(label2.mas_bottom).offset(-20);
            make.height.mas_equalTo(140);
    }];
  
    UILabel * label3  = [[UILabel alloc]init];
    label3.text = SQNSLocalString(@"生日");
    label3.font = FONT_MEDIUM(14);
    label3.textColor = SQColor999999;
    [bgView addSubview:label3];
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(16);
        make.top.equalTo(label2.mas_bottom).offset(146);
    }];
    [bgView addSubview:self.birthday];
    [self.birthday mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH-100);
            make.height.mas_equalTo(48);
            make.centerX.equalTo(bgView);
            make.top.equalTo(label3.mas_bottom).offset(8);
    }];
    
    UILabel * label4  = [[UILabel alloc]init];
    label4.text = SQNSLocalString(@"城市");
    label4.font = FONT_MEDIUM(14);
    label4.textColor = SQColor999999;
    [bgView addSubview:label4];
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(16);
        make.top.equalTo(label3.mas_bottom).offset(80);
    }];
    
    [bgView addSubview:self.city];
    [self.city mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH-100);
            make.height.mas_equalTo(48);
            make.centerX.equalTo(bgView);
            make.top.equalTo(label4.mas_bottom).offset(8);
    }];
    WS(weakSelf);
    [self.aboutMeTextView addTextDidChangeHandler:^(FSTextView *textView) {
        [weakSelf SQ_remarkHeight];
    }];
    [self SQ_Header];
}
-(void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:@"user/info" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [UserModel SQ_updateLocal:httpModel];
        //设置数据
        [self.headerView.headerImage sd_setImageWithURL:SQURLImage([UserModel share].portrait) placeholderImage:SQGetImage(@"1")];
        self.nameTextField.text = [UserModel share].name;
        self.city.text = [UserModel share].city;
        self.birthday.text = [UserModel share].birthday;
        self.aboutMeTextView.text = [UserModel share].remark;
        self.wxTextField.text = [UserModel share].wx;
        [self SQ_remarkHeight];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}

-(void)SQ_tijiaoButtonClick{
    [self.view endEditing:YES];
    if (self.isEdit) {
        //如果是后续编辑
        if (self.isHeaderImage) {
            [self SQ_headerViewuplodate];
        } else {
            [self SQ_Config:[UserModel share].portrait];
        }
    } else {
        if (!self.isHeaderImage) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请设置头像!")];
            return;
        }
        if (![self.nameTextField.text isNotEmpty]) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请设置昵称!")];
            return;
        }
        if (![self.genderView.gender isNotEmpty]) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"请设置性别!")];
            return;
        }
        [self SQ_headerViewuplodate];
    }
}
-(void)SQ_headerViewuplodate{
    WS(weakSelf);
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    [HttpTool SQ_Image:self.headerView.headerImage.image successBlock:^(BaseModel * _Nonnull httpModel) {
        [weakSelf SQ_Config:httpModel.data];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

-(void)SQ_Config:(NSString*)header{
    WS(weakSelf);
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:header forKey:@"portrait"];
    [dic setObject:self.nameTextField.text forKey:@"name"];
    if ([self.aboutMeTextView.formatText isNotEmpty]) {
        [dic setObject:self.aboutMeTextView.text forKey:@"remark"];
    }
    if ([self.birthday.text isNotEmpty]) {
        [dic setObject:self.birthday.text forKey:@"birthday"];
    }
    if ([self.wxTextField.text isNotEmpty]) {
        [dic setObject:self.wxTextField.text forKey:@"wx"];
    }
    [dic setObject:self.genderView.gender forKey:@"gender"];
    [HttpTool post:@"user/config" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        if (self.isEdit) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"更新成功")];
        } else {
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc]init]];
            weakSelf.view.window.rootViewController = nav;
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
   
}


-(void)SQ_remarkHeight{
    
    CGFloat h =  [self.aboutMeTextView sizeThatFits:CGSizeMake(SCREEN_WIDETH-108, MAXFLOAT)].height;
    if (h<40) {
        h = 40;
    }
    [self.aboutMeTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(h);
    }];
    [self.view layoutIfNeeded];
}
 


-(void)SQ_birthdayButtonClick{
    [self.view endEditing:YES];
    WS(weakSelf);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* selectValue = [NSString SQ_GetoutYear:-24];
    NSString* minDate = [NSString SQ_GetoutYear:-100];
    NSString* maxDate = [NSString SQ_GetoutYear:-18];
    [BRDatePickerView showDatePickerWithMode:BRDatePickerModeYMD title:@"出生日期" selectValue:selectValue minDate:[dateFormatter dateFromString:minDate] maxDate:[dateFormatter dateFromString:maxDate] isAutoSelect:YES resultBlock:^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
        weakSelf.birthday.text = selectValue;
    } resultRangeBlock:^(NSDate * _Nullable selectStartDate, NSDate * _Nullable selectEndDate, NSString * _Nullable selectValue) {
        
    }];
}
-(void)SQ_cityButtonClick{
    [self.view endEditing:YES];
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
    [[SQCLLocationManager sharedManager]SQ_Location:^(NSString * _Nonnull city) {
        weakSelf.city.text = city;
    }];
}


-(void)SQ_HeaderViewqButtonClick{
    WS(weakSelf);
    [self.view endEditing:YES];
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"设置头像") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_leftButtonClick];
    }];
    UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"相册") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_rightButtonClick];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}
-(void)SQ_leftButtonClick{
    [self presentViewController:self.imagePickerVc animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    WS(weakSelf);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
        if (photo == nil)
            {
                photo = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
        [weakSelf SQ_caijian:photo];
    }else
    {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"相册数据异常")];
    }
}

-(void)SQ_rightButtonClick{
    WS(weakSelf);
    TZImagePickerController * vc = [[TZImagePickerController alloc]init];
    vc.maxImagesCount = 1;
    [[Manager SQ_getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [weakSelf SQ_caijian:photos.firstObject];
    }];
}
//上传相册
-(void)SQ_caijian:(UIImage*)image{
   
    self.isHeaderImage = YES;
    self.headerView.headerImage.image = image;
}
#pragma mark --textField delegate
- (void)textFieldDidChange:(UITextField *)textField
{   NSString *lang = [[[UITextInputMode activeInputModes] firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (textField.text.length > 10) {
                textField.text = [textField.text substringToIndex:10];
            } else {
            }
        }
    } else{
        if (textField.text.length > 10) {
            textField.text = [textField.text substringToIndex:10];
        } else {
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.nameTextField resignFirstResponder];
    return YES;
}
- (HeaderView *)tijiaoBtn{
    if (!_tijiaoBtn) {
        _tijiaoBtn = [[HeaderView alloc]init];
        _tijiaoBtn.layer.cornerRadius = 15;
        _tijiaoBtn.layer.masksToBounds = YES;
        _tijiaoBtn.headerImage.image = SQGetImage(@"矩形备份 7");
        _tijiaoBtn.text = SQNSLocalString(@"提交");
        _tijiaoBtn.colorString = @"#FFFFFF";
        _tijiaoBtn.font = FONT_MEDIUM(14);
        [_tijiaoBtn.btn addTarget:self action:@selector(SQ_tijiaoButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tijiaoBtn;
}
 

- (HeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[HeaderView alloc]init];
        _headerView.contentMode = UIViewContentModeScaleAspectFill;
        _headerView.clipsToBounds = YES;
        [_headerView.btn addTarget:self action:@selector(SQ_HeaderViewqButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _headerView.layer.cornerRadius = 44;
        _headerView.layer.masksToBounds = YES;
    }
    return _headerView;
}
- (UIImagePickerController *)imagePickerVc{
    if (!_imagePickerVc) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        _imagePickerVc.allowsEditing = YES;
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
            _imagePickerVc.sourceType = sourceType;
        }
    }
    return _imagePickerVc;
}
- (UITextField *)nameTextField{
    if (!_nameTextField) {
        _nameTextField = [[UITextField alloc]init];
        _nameTextField.textAlignment = NSTextAlignmentCenter;
        _nameTextField.font = FONT_MEDIUM(16);
        _nameTextField.textColor = SQColor(@"#000000");
        _nameTextField.backgroundColor = SQColor(@"#FFFFFF");
        _nameTextField.layer.cornerRadius = 24;
        _nameTextField.layer.masksToBounds = YES;
        _nameTextField.returnKeyType = UIReturnKeyDone;
        _nameTextField.delegate = self;
        [_nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _nameTextField;
}
- (UITextField *)wxTextField{
    if (!_wxTextField) {
        _wxTextField = [[UITextField alloc]init];
        _wxTextField.textAlignment = NSTextAlignmentCenter;
        _wxTextField.font = FONT_MEDIUM(16);
        _wxTextField.textColor = SQColor(@"#000000");
        _wxTextField.backgroundColor = SQColor(@"#FFFFFF");
        _wxTextField.layer.cornerRadius = 24;
        _wxTextField.layer.masksToBounds = YES;
        _wxTextField.keyboardType = UIKeyboardTypeURL;
        _wxTextField.delegate = self;
    }
    return _wxTextField;
}
- (GenderPopView *)genderView{
    if (!_genderView) {
        _genderView = [[GenderPopView alloc]init];
    }
    return _genderView;
}
- (HeaderView *)birthday{
    if (!_birthday) {
        _birthday = [[HeaderView alloc]init];
        _birthday .font = FONT_MEDIUM(16);
        _birthday.backgroundColor = SQColor(@"#FFFFFF");
        _birthday.layer.cornerRadius = 24;
        _birthday.layer.masksToBounds = YES;
        _birthday.colorString = @"#000000";
        [_birthday.btn addTarget:self action:@selector(SQ_birthdayButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _birthday;
}

- (HeaderView *)city{
    if (!_city) {
        _city = [[HeaderView alloc]init];
        _city .font = FONT_MEDIUM(16);
        _city.backgroundColor = SQColor(@"#FFFFFF");
        _city.layer.cornerRadius = 24;
        _city.layer.masksToBounds = YES;
        _city.colorString = @"#000000";
        [_city.btn addTarget:self action:@selector(SQ_cityButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _city;
}
- (FSTextView *)aboutMeTextView{
    
    if (!_aboutMeTextView) {
        _aboutMeTextView = [[FSTextView alloc]init];
        _aboutMeTextView.backgroundColor  = UIColor.clearColor;
        _aboutMeTextView.textColor = UIColor.blackColor;
        _aboutMeTextView.maxLength = 300;
        _aboutMeTextView.textAlignment = NSTextAlignmentCenter;
        
    }
    return _aboutMeTextView;
}

@end
